/*
 * Copyright (c) 2009, ConnectCode Pte Ltd
 *                     http://www.webextractor360.com
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of ConnectCode nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY ConnectCode Pte Ltd ''AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL ConnectCode Pte Ltd BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 * 
 */

using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Threading;
using System.Windows.Forms;
using WebExtractor360.look4me.Action;
using WebExtractor360.look4me.Model;

namespace WebExtractor360.look4me.Framework
{    
    public partial class WorkerForm : TabForm
    {

        private System.Windows.Forms.Button startAsyncButton;
        private System.Windows.Forms.Button cancelAsyncButton;
        private System.Windows.Forms.ProgressBar mainProgressBar;
        private System.Windows.Forms.Label resultLabel;
        private System.ComponentModel.BackgroundWorker backgroundWorker1;



        private int m_actionValue;

        public int ActionValue
        {
            get
            {
                return m_actionValue;
            }
            set
            {
                m_actionValue = value;
            }
        }

        public WorkerForm()
        {    
            InitializeComponent();

            InitializeBackgoundWorker();

            SaveSettings = 1;
            SaveResults = 1;
            SaveLinksProcessed = 1;
            TextProcess = textBox2;
            TextResults = txtOutput;
            functionGroup.Text = "Input";
            System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = false;
        }

        // Set up the BackgroundWorker object by 
        // attaching event handlers. 
        private void InitializeBackgoundWorker()
        {
            backgroundWorker1.DoWork += 
                new DoWorkEventHandler(backgroundWorker1_DoWork);
            backgroundWorker1.RunWorkerCompleted += 
                new RunWorkerCompletedEventHandler(
            backgroundWorker1_RunWorkerCompleted);
            backgroundWorker1.ProgressChanged += 
                new ProgressChangedEventHandler(
            backgroundWorker1_ProgressChanged);
        }

        public bool GetFunctionGroupStatus()
        {
            return functionGroup.Enabled;
        }

        private void startAsyncButton_Click(System.Object sender, 
            System.EventArgs e)
        {
            // Reset the text in the result label.
            resultLabel.Text = String.Empty;

            this.startAsyncButton.Enabled = false;

            this.functionGroup.Enabled = false;
            this.cancelAsyncButton.Enabled = true;

            if (VerifyAndSetup()==1) // 1 for proceed
                backgroundWorker1.RunWorkerAsync();
        }


        private void cancelAsyncButton_Click(System.Object sender, 
            System.EventArgs e)
        {   

            this.backgroundWorker1.CancelAsync();


            cancelAsyncButton.Enabled = false;
        }


        private void backgroundWorker1_DoWork(object sender, 
            DoWorkEventArgs e)
        {   
            BackgroundWorker worker = sender as BackgroundWorker;
            WorkerExecute(worker, e);
        }

        private void backgroundWorker1_RunWorkerCompleted(
            object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                MessageBox.Show(e.Error.Message,"Error");
                resultLabel.Text = "Failed";
            }
            else if (e.Cancelled)
            {
                resultLabel.Text = "Cancelled";
            }
            else
            {
                resultLabel.Text = (string) e.Result;
            }


            this.functionGroup.Enabled = true;

            startAsyncButton.Enabled = true;
            cancelAsyncButton.Enabled = false;

            WorkerCompleted();
        }


        // This event handler updates the progress bar.
        private void backgroundWorker1_ProgressChanged(object sender,
            ProgressChangedEventArgs e)
        {
            this.mainProgressBar.Value = e.ProgressPercentage;
        }

        private ArrayList m_resultList;
        private SearchAction m_wpa;

        protected int VerifyAndSetup()
        {

            txtOutput.Text = "";
            textBox2.Text = "Started...";


            m_wpa = new SearchAction();
            m_wpa.MaxURI = (int)spnProcessUriMax.Value;
            m_wpa.Uri = txtUri.Text;

            tabControlResults.SelectedTab = tabPage2;

            m_wpa.Expressions = new string[1];
            m_wpa.Expressions[0]=textBoxExpressions.Text;

            return 1;
        }

        public void SetExpressions(string txt)
        {
            textBoxExpressions.Text = txt;
        }

        public void WorkerExecute(BackgroundWorker worker, DoWorkEventArgs e)
        {
            m_wpa.SetupWorkerEventForm(worker, e, this);
            m_wpa.Execute();
            m_resultList = m_wpa.GetResult();
        }

        public void WorkerCompleted()
        {
            IEnumerator ie = m_resultList.GetEnumerator();
            int firsttime = 1;
            while (ie.MoveNext())
            {
                if (firsttime == 1)
                {
                    if (Singleton.GetInstance().ShareClientModelHolder.ShareSearchOptionsVO.IncludePageInResults)
                        txtOutput.Text = ((ResultsValueObject)(ie.Current)).Result + "," + ((ResultsValueObject)(ie.Current)).WebPage;
                    else
                        txtOutput.Text = ((ResultsValueObject)(ie.Current)).Result;
                    firsttime = 0;
                }
                else
                {
                    if (Singleton.GetInstance().ShareClientModelHolder.ShareSearchOptionsVO.IncludePageInResults)
                        txtOutput.Text = txtOutput.Text + "\r\n" + ((ResultsValueObject)(ie.Current)).Result + "," + ((ResultsValueObject)(ie.Current)).WebPage;
                    else
                        txtOutput.Text = txtOutput.Text + "\r\n" + ((ResultsValueObject)(ie.Current)).Result;
                }
            }
            tabControlResults.SelectedTab = tabPage1;

            countlabel.Text = m_resultList.Count.ToString();
        }

        public void CommonCallBack(ValueObject vo)
        {
            ExtractorCurrentResultsValueObject rvo = (ExtractorCurrentResultsValueObject)vo;
            textBox2.Text = rvo.Links + "\r\n" + textBox2.Text;
        }

        override public void doPopulateProfile()
        {

            ProfileValueObjectHolder = new ProfileValueObject();
            ProfileValueObjectHolder.ProfileAction = FormsActivator.EXTRACTORFORM;
            ProfileValueObjectHolder.MaxURL = Convert.ToInt32(spnProcessUriMax.Value);
            ProfileValueObjectHolder.ProfileURL = txtUri.Text;
            ProfileValueObjectHolder.Expressions = new string[1];
            ProfileValueObjectHolder.Expressions[0] = textBoxExpressions.Text;
        }

        override public void doPopulateForm()
        {
            if (GetFunctionGroupStatus() == false)
            {
                MessageBox.Show("This Operation is currently not allowed as a background job for this Window is running.");
                return;
            }

            spnProcessUriMax.Value = Convert.ToDecimal(ProfileValueObjectHolder.MaxURL);
            txtUri.Text = ProfileValueObjectHolder.ProfileURL;

            textBoxExpressions.Text = ProfileValueObjectHolder.Expressions[0];
        }

        private void WorkerForm_Load(object sender, EventArgs e)
        {

        }

    }
}

